package com.clean.cleantotal.compores.compress

import android.graphics.Bitmap
import android.os.Bundle
import android.os.Environment
import androidx.core.view.isVisible
import androidx.lifecycle.lifecycleScope
import coil.load
import coil.transform.RoundedCornersTransformation
import com.blankj.utilcode.util.FileUtils
import com.blankj.utilcode.util.ImageUtils
import com.blankj.utilcode.util.SPUtils
import com.clean.cleantotal.R
import com.clean.cleantotal.base.BaseActivity
import com.clean.cleantotal.bean.FunType
import com.clean.cleantotal.databinding.ActivityCompressDetailsBinding
import com.clean.cleantotal.compores.result.ResultActivity
import com.clean.cleantotal.utils.CompressUtils
import com.clean.cleantotal.utils.FormatterSize
import com.clean.cleantotal.utils.Utils
import com.luck.picture.lib.entity.LocalMedia
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext

class CompressDetailsActivity : BaseActivity<ActivityCompressDetailsBinding>() {
    override val viewBinding: ActivityCompressDetailsBinding
        get() = ActivityCompressDetailsBinding.inflate(layoutInflater)

    private var media: LocalMedia? = null
    private var state: String = "before"
    private var quality = 100
    private var format = Bitmap.CompressFormat.JPEG
    private var originPath = ""
    private var originBitmap: Bitmap? = null
    private var fileName: String = ""

    override fun initParams(extras: Bundle?) {
        super.initParams(extras)
        extras?.let {
            media = it.getParcelable("media")
            state = it.getString("state", "before")
        }
    }

    override fun initView() {
        mBinding.loadingLayout.scanLayout.isVisible = false
        try {
            originPath = media?.realPath ?: ""
            fileName = media?.fileName ?: "${System.currentTimeMillis()}"
            originBitmap = ImageUtils.getBitmap(originPath)

            quality = CompressUtils.getQ(originPath)
            format = CompressUtils.getFormat(originPath)

            mBinding.back.setOnClickListener { onBackPressed() }

            when (state) {
                "before" -> {
                    mBinding.compress.isVisible = true
                    media?.let {
                        val compressedImage =
                            CompressUtils.getCompressedImage(originBitmap, quality, originPath)
                        val compressedImageSize =
                            CompressUtils.getCompressedImageSize(originBitmap, quality, originPath)
                        mBinding.ivBefore.load(originBitmap) {
                            transformations(RoundedCornersTransformation(36f))
                        }
                        mBinding.tvBefore.text =
                            "Before ${FormatterSize.formatFileSize(this, it.size)}"
                        mBinding.ivAfter.load(compressedImage) {
                            transformations(RoundedCornersTransformation(36f))
                        }
                        mBinding.tvAfter.text =
                            "After ${FormatterSize.formatFileSize(this, compressedImageSize)}"
                    }
                }

                else -> {
                    mBinding.compress.isVisible = false
                    val beforePath = SPUtils.getInstance().getString(fileName)
                    val beforeSize = FileUtils.getLength(beforePath)
                    val afterSize = FileUtils.getLength(originPath)
                    mBinding.ivBefore.load(beforePath) {
                        transformations(RoundedCornersTransformation(36f))
                    }
                    mBinding.tvBefore.text =
                        "Before ${FormatterSize.formatFileSize(this, beforeSize)}"
                    mBinding.ivAfter.load(originPath) {
                        transformations(RoundedCornersTransformation(36f))
                    }
                    mBinding.tvAfter.text = "After ${FormatterSize.formatFileSize(this, afterSize)}"
                }
            }
            mBinding.compress.setOnClickListener {
                mBinding.loadingLayout.scanLayout.isVisible = true
                Utils.showScanDialog(this, FunType.COMPRESS, mBinding.loadingLayout.scanLayout, {
                    animal = it
                }) {
                    openActivity(ResultActivity::class.java, Bundle().apply {
                        putSerializable("funType", FunType.COMPRESS)
                        putString("title", mBinding.title.text.toString().trim())
                        finish()
                    })
                }
                lifecycleScope.launch(Dispatchers.IO) {
                    try {
                        val savePath = Environment.getExternalStoragePublicDirectory(
                            Environment.DIRECTORY_PICTURES
                        ).absolutePath + "/${getString(R.string.app_name)}/" + fileName
                        val isSuccess = CompressUtils.saveCompressPhoto(
                            originBitmap, savePath, format, quality
                        )
                        if (isSuccess) {
                            media?.let {
                                SPUtils.getInstance().put(it.fileName, originPath)
                            }
                        }
                        withContext(Dispatchers.Main) {
                            animal?.duration = 2000
                        }
                    } catch (e: Exception) {
                        e.printStackTrace()
                        animal?.duration = 1000
                    }
                }
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

}